import { defineStore } from "pinia";
import {ref} from 'vue'
import {loginAPI} from '@/network/user.js'
import { useCartStore } from "./cartStore";
import { mergeCartAPI } from "@/network/cart";
export const useUserStore = defineStore('user', () => {
    // 1. 定义管理用户数据的state
    const userInfo = ref({})

    // 2. 获取用户数据action函数
    const {cartList} = useCartStore()
    // console.log(cartList);
   async function getUserInfo(account, password) {
        const res = await loginAPI(account, password)
        // console.log(res);
        userInfo.value = res.result
        // 登录合并购物车
       await mergeCartAPI(cartList.map((item) => { // 由响应式对象包着的ref对象，不用.value
           
            return {
                skuId: item.skuId,
                count: item.count,
                selected: item.selected,
            }
        }))
        // 更新
        updateNewList()
        
    }
    const {clearCart, updateNewList} = useCartStore()
    // 3. 用户退出登录，清除用户信息
        function clearUserInfo() {
            userInfo.value = {}
            // 退出登录删除购物车数据
            clearCart()
            // console.log('shanchu ');
        }

    return {
        getUserInfo,
        userInfo,
        clearUserInfo
    }
}, {
    persist: true
})